import urllib, urllib2, sys, optparse, ConfigParser, logging

from xml.etree import ElementTree as etree

# url to which archival requests are made
request_url = "http://hanzoweb.com/xml/gather/"

# data item names used when requesting an archival operation
request_items = (
   "url",
   "username",
   "key",
   "tags",
   "name",
   "description",
   "scope",
   "visibility"
)

# status check codes & explanations
statuscodes = {
   "NEW": "queued - not yet retrieving",
   "GATHERING": "retrieving - gather in progress",
   "TRANSFERRING": "retrieved - transferring to archive",
   "COMPLETED": "ready - available for download",
   "ERROR": "error - please wait for this to be retried"
}


example = """<?xml version="1.0" encoding="UTF-8"?>
<response status="ok">
    <item id="">
    <instance id="2678">
      <status>NEW</status>
    </instance>
  </item>
</response>
"""


def parse_response(xmlstr):
   "return (status, id)"
   try:
      doc = etree.fromstring(xmlstr)
      result = doc.attrib["status"]
   except Exception, e:
      raise Exception("problem parsing hanzoweb response: %s" % xmlstr)

   if result == "error":
      error = doc.find("error").text
      raise Exception("api call error: %s" % error)

   status = doc.find("item/instance/status").text
   id = doc.find("item/instance").attrib["id"]
   return (status, id)


def send_request(url, username, key, tags, name, description, scope, visibility, logger=None):
   """Send a request to hanzoweb.
   
   username = hanzoweb username
   key = 40 hex digit developer key
   url = the url to gather
   tags = a space separated list of alphanumeric tags
   name = the title of the site
   description = a short plain text description, comments or notes
   scope = 'bookmark' | 'page' | 'context' | 'website'
   visibility = 'private' | 'public'
   """

   if not logger:
      logger = logging.root

   data = dict([(item, eval(item)) for item in request_items if eval(item) is not None])
   postdata = urllib.urlencode(data)
   request = urllib2.Request(request_url)
   request.add_data(postdata)
   try:
      result = urllib2.urlopen(request)
   except Exception, e:
      raise Exception("problem communicating with hanzoweb service: %s" % e)

   if result.msg == "OK":
      return parse_response(result.read())
   else:
      raise Exception("request failure: %s" % result.msg)
